package com.etime.shycourse.services.coupons.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etime.shycourse.services.coupons.interfaces.CouponactivityrefServices;
import com.etime.shycourse.dao.CouponactivityrefMapper;
import com.etime.shycourse.pojo.Couponactivityref;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * @ClassName : CouponactivityrefServicesImpl  //类名
 * @Description :  优惠券与活动的对应关系 //描述
 * @Author : W //作者
 * @Date: 2022/3/21  14:25
 */
@Service
public class CouponactivityrefServicesImpl implements CouponactivityrefServices {
    @Autowired
    private CouponactivityrefMapper mapper;

    /**
     * 查询活动与优惠券是否存在对应关系
     * 存在返回 第一个对应关系
     * 不存在返回 null
     *
     * @param activityId 活动id
     * @return Couponactivityref
     */
    @Override
    public List<Couponactivityref> selectActivityRefById(Integer activityId) {
        List<Couponactivityref> list = mapper.selectList (new QueryWrapper<Couponactivityref> ().eq ("cactivityid", activityId));
        if (list.size () > 0) {
            return list;
        }
        return null;
    }

    /**
     * 插入活动与优惠券是否存在对应关系
     *
     * @param couponactivityref
     * @return 1 成功 0 失败
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer insertCouponActivity(List<Couponactivityref> couponactivityref) {
        if (couponactivityref.size () > 0) {
            // 先删除所有的活动与优惠券是否存在对应关系
            mapper.delete (new QueryWrapper<Couponactivityref> ().eq ("cactivityid", couponactivityref.get (0).getCactivityid ()));
            try {
                couponactivityref.forEach (l -> {
                    mapper.insert (l);
                });
                return 1;
            } catch (Exception e) {
                e.printStackTrace ();
                // @Transactional和try catch捕获异常会让注解失效
                TransactionAspectSupport.currentTransactionStatus ().setRollbackOnly ();
                return 0;
            }
        }
        return 0;
    }
}

